package com.zhou.util;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author lang.zhou
 * @date 2019/11/8
 */
public class StringTool extends StringUtils{
    public static final Pattern CSS_STYLE_HTML = Pattern.compile("<style>.*</style>");
    public static final Pattern HEADER_STYLE_HTML = Pattern.compile("<head>.*</head>");
    public static Pattern TAG_PATTERN = Pattern.compile("<[^>]+>");

    public static final String HTTP = "http://";
    public static final String HTTPS = "https://";
    public static final String WWW = "www.";

    public static String safeToString(Object o,String dv){
        return o==null ? dv : o.toString();
    }
    public static String safeToString(Object o){
        return safeToString(o,"");
    }
    /**
     * 对引号以及尖括号进行转义
     */
    public static String replaceXmlEscape(String a){
        return a.replace("&lt;","<").replace("&gt;",">")
                .replace("&amp;","&").replace("&apos;","'").replace("&quot;","\"");
    }
    /**
     * 对引号以及尖括号进行反转义
     */
    public static String toXmlEscape(String a){
        return a.replace("<","&lt;").replace(">","&gt;")
                .replace("&","&amp;").replace("'","&apos;").replace("\"","&quot;");
    }

    /**
     * 去掉字符串中的数字，经过测试速度快于replaceAll("\\d","")
     */
    public static String replaceNum(String str){
        byte[] st=str.getBytes();
        byte[] s=new byte[st.length];
        int i=0;
        for (byte aSt : st) {
            if (aSt < 48 || aSt > 57) {
                s[i++]=aSt;
            }
        }
        byte[] res=new byte[i];
        System.arraycopy(s, 0, res, 0, i);
        return new String(res);
    }
    /**
     * 只保留字符串中的数字
     */
    public static String filterNum(String str){
        byte[] st=str.getBytes();
        byte[] s=new byte[st.length];
        int i=0;
        for (byte aSt : st) {
            if (aSt >= 48 && aSt <= 57) {
                s[i++]=aSt;
            }
        }
        byte[] res=new byte[i];
        System.arraycopy(s, 0, res, 0, i);
        return new String(res);
    }

    /**
     * 生成uuid
     */
    public static String uuid(){
        return UUID.randomUUID().toString().replace("-","");
    }

    /**
     * 获得字符串的字节长度
     * @param charLen   一个中文字符占的字节数
     */
    public static int getStringLength(String string, int charLen) {
        int length = 0;
        for(int i = 0; i < string.length(); ++i) {
            if (string.charAt(i) >= 127) {
                length += charLen;
            } else {
                ++length;
            }
        }
        return length;
    }
    /**
     * 获得字符串字节长度
     */
    public static int getStringLength(String val,String charset){
        if(isNotEmpty(val)){
            try {
                return val.getBytes(charset).length;
            } catch (UnsupportedEncodingException e) {
                return getStringLength(val,3);
            }
        }
        return 0;
    }
    /**
     * 从字符串中截取一个最大长度的字符串
     * @param s         原始字符串
     * @param maxLen    保留的最大长度
     */
    public static String maxLen(String s,int maxLen){
        return s != null ? s.substring(0, Math.min(s.length(), maxLen)) : s;
    }

    /**
     * 将字符串转为*号
     */
    public static String toMask(String v){
        String s1 = safeToString(v,"");
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < s1.length(); i++) {
            s.append("*");
        }
        return s.toString();
    }
    /**
     * 将字符串重复n次并连接
     */
    public static String getStr(String v, int n){
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < n; i++) {
            s.append(v);
        }
        return s.toString();
    }

    /**
     * 去掉字符串中的超文本标记，提取纯文本
     */
    public static String removeHtml(String str){
        if(isNotBlank(str)){
            str = CSS_STYLE_HTML.matcher(str).replaceAll("");
            str = HEADER_STYLE_HTML.matcher(str).replaceAll("");
            str = TAG_PATTERN.matcher(str).replaceAll("");
        }
        return str;
    }
    /**
     * 將excel中列字母转化为数字
     */
    public static int excelColToNum(String s){
        int num ;
        int result = 0;
        for(int i = 0; i < s.length(); i++) {
            char ch = s.charAt(s.length() - i - 1);
            num = ch - 'A' + 1;
            num *= Math.pow(26, i);
            result += num;
        }
        return result-1;
    }

    public static String replaceVariables(String str, Map<?,?> data) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(str)) {
            int k = 0;
            int j = 0;
            int i = str.indexOf("${");

            while(i >= 0 && j >= 0) {
                sb.append(str, j, i);
                j = str.indexOf("}", i);
                if (j > 0) {
                    String name = str.substring(i + 2, j);
                    if (data.containsKey(name)) {
                        sb.append(safeToString(data.get(name), ""));
                    }

                    i = str.indexOf("${", j + 1);
                    k = j + 1;
                    ++j;
                }
            }

            sb.append(str.substring(k));
        }

        return sb.toString();
    }

    public static String buildKey(Map<String,Object> t, List<String> cols){
        StringJoiner b = new StringJoiner("||-||");
        for (String col : cols) {
            b.add(MapUtils.getString(t,col));
        }
        return b.toString();
    }

    public static List<String> extraKey(String v){
        List<String> list = Arrays.asList(v.split("\\|\\|-\\|\\|"));
        return new ArrayList<>(list);
    }

    public static String removeFirst(String str,String a){
        int ind = str.indexOf(a);
        if(ind == 0){
            str = str.substring(0,a.length());
        }
        return str;
    }
    public static String removeLast(String str,String a){
        int ind = str.lastIndexOf(a);
        if(str.endsWith(a)){
            str = str.substring(ind,a.length());
        }
        return str;
    }

    /**
     * 是否为http(s)://开头
     *
     * @param link 链接
     * @return 结果
     */
    public static boolean isHttp(String link) {
        return StringUtils.startsWithAny(link, HTTP, HTTPS);
    }

    public static String concat(String... arr) {
        StringBuilder b = new StringBuilder();
        for (String s : arr) {
            b.append(s);
        }
        return b.toString();
    }

}
